<template>
  <q-popup-proxy v-model="popupVisible" :offset="[0, 0]" :target="targetEl" anchor="bottom middle" breakpoint="0"
                 class="bg-grey-3 shadow-8" maxWidth="45vw" no-parent-event self="top middle" touch-position
                 transition-hide="jump-up" transition-show="jump-down">
    <q-card class="bg-grey-3" flat>
      <q-bar class="sticky-top bg-grey-4">
        <q-space></q-space>
        <transition appear name="q-transition--jump-left">
          <span v-if="isCopy" class="text-caption text-primary">Copied to clipboard</span>
        </transition>
        <q-icon class="cursor-pointer cursor-hover" color="primary" name="copy_all" size="1.5rem"
                @click.stop="handleCopy">
          <q-tooltip v-bind="$tooltipAttr">Copied to clipboard</q-tooltip>
        </q-icon>
      </q-bar>
      <QCodePrism :code="jsonInfo"></QCodePrism>
    </q-card>
  </q-popup-proxy>
</template>

<script setup>
import { copyToClipboard } from 'quasar'
import { onUnmounted, ref, watch } from 'vue'

const props = defineProps({ jsonInfo: String, modelValue: Boolean, targetEl: [String, Boolean] })
const emits = defineEmits(['update:modelValue'])

const isCopy = ref(false)
const popupVisible = ref(false)

watch(() => props.modelValue, val => {
  if (props.jsonInfo) popupVisible.value = val
  else emits('update:modelValue', popupVisible.value)
})
watch(popupVisible, val => emits('update:modelValue', val))
onUnmounted(() => emits('update:modelValue', false))

const handleCopy = () => {
  const { jsonInfo = '' } = props
  copyToClipboard(jsonInfo).then(() => {
    isCopy.value = true
    const timer = setTimeout(() => {
      isCopy.value = false
      clearTimeout(timer)
      emits('update:modelValue', false)
    }, 1000)
  })
}
</script>

<style lang="scss" scoped>
.language-json {
  overflow-x: hidden;
}
</style>